package org.jeecg.modules.wlhy.hycarrier.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.third.aliyunocr.AliyunOcrService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.hybank.entity.HyBank;
import org.jeecg.modules.wlhy.hybank.service.IHyBankService;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.BankTypeUtil;
import org.jeecg.modules.wlhy.utils.DataMaskingUtil;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 承运商
 * @Author: duanlikao
 * @Date:   2020-12-01
 * @Version: V1.0
 */
@Api(tags="承运商")
@RestController
@RequestMapping("/hycarrier/hyCarrier")
@Slf4j
public class HyCarrierController extends JeecgController<HyCarrier, IHyCarrierService> {
	@Autowired
	private IHyCarrierService hyCarrierService;

	@Autowired
	private UserUtil userUtil;

	@Autowired
	private IHyOrderService hyOrderService;

	@Autowired
	private IHyShippingNoteService hyShippingNoteService;

	@Autowired
	private AliyunOcrService aliyunOcrService;

	@Resource
	private IHySettingService settingService;

	@Autowired
	private IHyBankService hyBankService;

	/**
	 * 分页列表查询
	 *
	 * @param hyCarrier
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="承运商-分页列表查询", notes="承运商-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyCarrier hyCarrier,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HyCarrier> queryWrapper = QueryGenerator.initQueryWrapper(hyCarrier, req.getParameterMap());
		HyCustomer customer = userUtil.getCustomer();
		if(customer!=null){
			queryWrapper.eq("customer_id",customer.getId());
		}

		Page<HyCarrier> page = new Page<HyCarrier>(pageNo, pageSize);
		IPage<HyCarrier> pageList = hyCarrierService.page(page, queryWrapper);

		//如果开启系统脱敏
		String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
		if("1".equals(dataMaskingFlag)) {
			for (HyCarrier dto : pageList.getRecords()) {
				dto.setTel(DataMaskingUtil.phoneMasking(dto.getTel()));
				dto.setIdcard(DataMaskingUtil.idcardMasking(dto.getIdcard()));
				dto.setBankNum(DataMaskingUtil.idcardMasking(dto.getBankNum()));
			}
		}


		return Result.OK(pageList);
	}

	@ApiOperation(value="车队长统计", notes="车队长统计")
	@GetMapping(value = "/tj")
	public Result<?> tj(HyCarrier hyCarrier,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HyCarrier> queryWrapper = QueryGenerator.initQueryWrapper(hyCarrier, req.getParameterMap());
		HyCustomer customer = userUtil.getCustomer();
		if(customer!=null){
			queryWrapper.eq("customer_id",customer.getId());
		}
		Page<HyCarrier> page = new Page<HyCarrier>(pageNo, pageSize);
		//todo
		IPage<HyCarrier> pageList = hyCarrierService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	/**
	 *   添加
	 *
	 * @param hyCarrier
	 * @return
	 */
	@AutoLog(value = "承运商-添加")
	@ApiOperation(value="承运商-添加", notes="承运商-添加")
	@PostMapping(value = "/add")
	@RequiresPermissions("sys:carrier:add")
	public Result<?> add(@RequestBody HyCarrier hyCarrier) {
		HyCustomer customer = userUtil.getCustomer();
		if(customer!=null){
			hyCarrier.setCustomerId(customer.getId());
		}

		String bankName = hyCarrier.getBankName();
		String bankNum = hyCarrier.getBankNum();
		String bankType = hyCarrier.getBankType();

		if(StringUtils.isBlank(bankName)){
			return Result.error("账户名不能为空");
		}
		if(StringUtils.isBlank(bankNum)){
			return Result.error("银行卡号不能为空");
		}
		if(StringUtils.isEmpty(bankType)){
			return Result.error("银行类别不能为空");
		}
		if(!BankTypeUtil.checkBankType(bankType)){
			return Result.error("银行类别错误");
		}

		HyBank bank1 = hyBankService.getByBankType(hyCarrier.getBankType());
		if (bank1 == null) {
			return Result.error("银行行号信息缺失,请联系管理员进行添加");
		}else {
			hyCarrier.setCrBankNo(bank1.getBankHh());
		}

		bankName = bankName.trim();
		bankNum = bankNum.trim();
		hyCarrier.setBankName(bankName);
		hyCarrier.setBankNum(bankNum.replaceAll(" ",""));

		//Added at 2023-09-09 for 判断必须绑定本人银行卡
		if ("1".equals(settingService.getSettingValueByTag2("self_bankcard"))) {
			if (!hyCarrier.getCarrierName().equals(bankName)) {
				return Result.error("当前系统已限定绑定本人银行卡，请联系平台管理员");
			}
		}

		if(HyCfgUtil.isUsed2("checkBankCard")){
			if(StringUtils.isEmpty(hyCarrier.getIdcard())){
				return Result.error("开户人身份证号不能为空");
			}
			//验证银行卡三要素
			Result<?> result = aliyunOcrService.ToolsBank(hyCarrier.getIdcard(), hyCarrier.getBankName(), hyCarrier.getBankNum());
			if(!result.isSuccess()){
				return result;
			}
			JSONObject ret = (JSONObject) result.getResult();
			String bank = ret.getString("bank");
			bankType = BankTypeUtil.getBankTypeByBankName2(bank);
			if(StringUtils.isEmpty(bankType)){
				return Result.error("未找到对应的银行卡类别,请联系管理员,银行名称:" + bank);
			}
			hyCarrier.setBankType(bankType);
		}

		hyCarrierService.save(hyCarrier);
		return Result.OK("添加成功！");
	}



	/**
	 *  编辑
	 *
	 * @param hyCarrier
	 * @return
	 */
	@AutoLog(value = "承运商-编辑")
	@ApiOperation(value="承运商-编辑", notes="承运商-编辑")
	@PutMapping(value = "/edit")
	@RequiresPermissions("sys:carrier:edit")
	@CacheEvict(value = CacheConstant.SYS_DICT_TABLE_CACHE ,key = "'SimpleKey [hy_carrier,carrier_name,id,' + #hyCarrier.id + ']'")
	public Result<?> edit(@RequestBody HyCarrier hyCarrier) {
		HyCustomer customer = userUtil.getCustomer();
		if(customer!=null){
			if(!StringUtils.equals(hyCarrier.getCustomerId(),customer.getId())){
				return Result.error("货主信息错误!");
			}
		}

		String bankName = hyCarrier.getBankName();
		String bankNum = hyCarrier.getBankNum();
		String bankType = hyCarrier.getBankType();

		if(StringUtils.isBlank(bankName)){
			return Result.error("姓名不能为空");
		}
		if(StringUtils.isBlank(bankNum)){
			return Result.error("银行卡号不能为空");
		}
		if(StringUtils.isEmpty(bankType)){
			return Result.error("银行类别不能为空");
		}
		if(!BankTypeUtil.checkBankType(bankType)){
			return Result.error("银行类别错误");
		}

		bankName = bankName.trim();
		bankNum = bankNum.trim();
		hyCarrier.setBankName(bankName);
		hyCarrier.setBankNum(bankNum.replaceAll(" ",""));

		if(HyCfgUtil.isUsed2("checkBankCard")){
			if(StringUtils.isEmpty(hyCarrier.getIdcard())){
				return Result.error("开户人身份证号不能为空");
			}
			//验证银行卡三要素
			Result<?> result = aliyunOcrService.ToolsBank(hyCarrier.getIdcard(), hyCarrier.getBankName(), hyCarrier.getBankNum());
			if(!result.isSuccess()){
				return result;
			}
			JSONObject ret = (JSONObject) result.getResult();
			String bank = ret.getString("bank");
			bankType = BankTypeUtil.getBankTypeByBankName2(bank);
			if(StringUtils.isEmpty(bankType)){
				return Result.error("未找到对应的银行卡类别,请联系管理员,银行名称:" + bank);
			}
			hyCarrier.setBankType(bankType);
		}

		//Added at 2023-09-09 for 判断必须绑定本人银行卡
		if ("1".equals(settingService.getSettingValueByTag2("self_bankcard"))) {
			if (!hyCarrier.getCarrierName().equals(bankName)) {
				return Result.error("当前系统已限定绑定本人银行卡，请联系平台管理员");
			}
		}

		hyCarrierService.updateById(hyCarrier);
		return Result.OK("编辑成功！");
	}

//	private Result <?> getCheckResult( HyCarrier hyCarrier) {
//		Result<JSONObject> result = new Result<JSONObject>();
//		if(StringUtils.isNotEmpty(hyCarrier.getBankNum())){
//			hyCarrier.setBankNum(
//					hyCarrier.getBankNum().replaceAll(" ","")
//			);
//		}
//		HyCarrier hyCarrierDb = null;
//		if(StringUtils.isNotEmpty(hyCarrier.getId()) ){
//			hyCarrierDb = hyCarrierService.getById(hyCarrier.getId());
//			if(hyCarrierDb==null) {
//				throw new JeecgBootException("未找到对应数据");
//			}
//		}
//
//		if(StringUtils.isNotEmpty(hyCarrier.getTel()) &&  hyCarrier.getTel().length() != 11){
//			throw new JeecgBootException("手机号应为11位数。");
//		}
//		if (StringUtils.isNotEmpty(hyCarrier.getTel() ) &&  !hyCarrier.getTel().matches(CommonConstant.REGEX_MOBILE)) {
//			throw new JeecgBootException("手机号格式错误！");
//		}
//
//		if( StringUtils.isEmpty(hyCarrier.getIdcard())){
//			throw new JeecgBootException("请填写身份证号！");
//		}
//		if(hyCarrier.getIdcard() != null &&  hyCarrier.getIdcard().length() != 15 &&
//				hyCarrier.getIdcard().length() != 18){
//			throw new JeecgBootException("身份证应为15位或者18位。");
//		}
//		if(!IDUtils.isIDNumber(hyCarrier.getIdcard())){
//			throw new JeecgBootException("请填写正确身份证！");
//		}
//
//		String bankType = hyCarrier.getBankType();
//		if(StringUtils.isEmpty(bankType)){
//			throw new JeecgBootException("银行类型不能为空！");
//		}
//
//		String bankNo = BankTypeUtil.getBankNo(bankType);
//		if(StringUtils.isEmpty(bankNo)){
//			throw new JeecgBootException("暂不支持该银行！");
//		}
//
//		String bankInfo  = aliyunOcrService.ToolsBank(hyCarrier.getIdcard(),
//				hyCarrier.getBankName(),hyCarrier.getBankNum());
//		String bankName = "";
//		if(StringUtils.isNotEmpty(bankInfo)) {
//			JSONObject jsonObject = JSONObject.parseObject(bankInfo);
//			String status = jsonObject.get("status") != null ? jsonObject.get("status").toString() : "";
//			if(StringUtils.isNotEmpty(status)  && !status.equals("01")){
//				//jsonObject.get("msg").toString()
//				//"请重新输入开卡姓名，开卡身份证号，开卡银行卡号！"
//				return Result.error(jsonObject.get("msg").toString());
//			}
//
//			if(StringUtils.isNotEmpty(status)  && status.equals("01")){
//				bankName = jsonObject.get("bank").toString();
//			}
//
//		}
//		if(StringUtils.isEmpty(bankName)){
//			return Result.error("获取开户行信息失败,请稍后再试或者联系客服！");
//		}
//
//		return null;
//	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "承运商-通过id删除")
	@ApiOperation(value="承运商-通过id删除", notes="承运商-通过id删除")
	@DeleteMapping(value = "/delete")
	@RequiresPermissions("sys:carrier:delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {

		int count = hyOrderService.count(new QueryWrapper<HyOrder>().eq("carrier_id",id));
		int count1 = hyShippingNoteService.count(new QueryWrapper<HyShippingNote>().eq("carrier_id",id));
		if(count==0 && count1==0){
			hyCarrierService.removeById(id);
			return Result.OK("删除成功!");
		}else{
			return Result.error("该车队长有关联货源和运单不允许删除!");
		}


	}
//
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "承运商-批量删除")
//	@ApiOperation(value="承运商-批量删除", notes="承运商-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	@RequiresPermissions("sys:carrier:deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyCarrierService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="承运商-通过id查询", notes="承运商-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HyCarrier hyCarrier = hyCarrierService.getById(id);
		if(hyCarrier==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hyCarrier);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hyCarrier
    */
    @RequestMapping(value = "/exportXls")
	@RequiresPermissions("sys:carrier:exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HyCarrier hyCarrier) {
        return super.exportXls(request, hyCarrier, HyCarrier.class, "承运商");
    }

//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//	@RequiresPermissions("sys:carrier:importExcel")
//	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, HyCarrier.class);
//    }

}
